<template>
  <div>
    <el-tag effect="dark" class="my-tag">
      <svg class="icon" width="20" height="20" style="vertical-align: -3px">
        <use xlink:href="#icon-wenzhang"/>
      </svg>
      文章信息
    </el-tag>
    <el-form
      :model="article"
      :rules="rules"
      ref="ruleForm"
      label-width="150px"
      class="demo-ruleForm"
    >
      <el-form-item label="标题" prop="articleTitle">
        <el-input maxlength="30" v-model="article.articleTitle"></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="articleContent">
        <mavon-editor ref="md" @imgAdd="imgAdd" v-model="article.articleContent"/>
      </el-form-item>

      <el-form-item label="是否启用评论" prop="commentStatus">
        <el-tag :type="article.commentStatus === false ? 'danger' : 'success'" disable-transitions>
          {{ article.commentStatus === false ? "否" : "是" }}
        </el-tag>
        <el-switch v-model="article.commentStatus"></el-switch>
      </el-form-item>

      <el-form-item label="是否推荐" prop="recommendStatus">
        <el-tag :type="article.recommendStatus === false ? 'danger' : 'success'" disable-transitions>
          {{ article.recommendStatus === false ? "否" : "是" }}
        </el-tag>
        <el-switch v-model="article.recommendStatus"></el-switch>
      </el-form-item>

      <el-form-item label="是否可见" prop="viewStatus">
        <el-tag :type="article.viewStatus === false ? 'danger' : 'success'" disable-transitions>
          {{ article.viewStatus === false ? "否" : "是" }}
        </el-tag>
        <el-switch v-model="article.viewStatus"></el-switch>
      </el-form-item>

      <el-form-item label="是否加密" prop="encoderStatus">
        <el-tag :type="article.encoderStatus === false ? 'danger' : 'success'" disable-transitions>
          {{ article.encoderStatus === false ? "否" : "是" }}
        </el-tag>
        <el-switch v-model="article.encoderStatus"></el-switch>
      </el-form-item>

      <el-form-item label="访问密码" prop="password">
        <el-input maxlength="30" v-model="article.password"></el-input>
      </el-form-item>
      <el-form-item label="封面" prop="articleCover">
        <div style="display: flex">
          <el-input v-model="article.articleCover"></el-input>
          <el-image
            class="table-td-thumb"
            lazy
            style="margin-left: 10px"
            :preview-src-list="[article.articleCover]"
            :src="article.articleCover"
            fit="cover"
          ></el-image>
        </div>
        <uploadPicture
          style="margin-top: 10px"
          @addPicture="addArticleCover"
          :maxSize="2"
          :maxNumber="1"
        ></uploadPicture>
      </el-form-item>
      <el-form-item label="分类" prop="sortId">
        <el-select v-model="article.sortId" @change="sortChange" placeholder="请选择分类">
          <el-option
            v-for="item in sorts"
            :key="item.value"
            :label="item.value"
            :value="item.key"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="labelId">
        <el-select v-model="article.labelId" :disabled="this.labelDisable" placeholder="请选择标签">
          <el-option
            v-for="item in labels"
            :key="item.value"
            :label="item.value"
            :value="item.key"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="myCenter" style="margin-bottom: 22px">
      <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      <el-button type="danger" @click="resetForm('ruleForm')">重置所有修改</el-button>
    </div>
  </div>
</template>

<script>
const uploadPicture = () => import("../../common/uploadPicture.vue");

export default {
  components: {
    uploadPicture,
  },
  data() {
    return {
      id: this.$route.query.id,
      type: "detail",
      article: {
        articleTitle: "",
        articleContent: "",
        commentStatus: true,
        recommendStatus: false,
        viewStatus: true,
        encoderStatus: false,
        password: "",
        articleCover: "",
        sortId: null,
        labelId: null,
      },
      sorts: [],
      labels: [],
      labelsTemp: [],
      labelDisable: true,
      rules: {
        articleTitle: [
          {required: true, message: "请输入标题", trigger: "change"},
        ],
        articleContent: [
          {required: true, message: "请输入内容", trigger: "change"},
        ],
        commentStatus: [
          {required: true, message: "是否启用评论", trigger: "change"},
        ],
        recommendStatus: [
          {required: true, message: "是否推荐", trigger: "change"},
        ],
        viewStatus: [
          {required: true, message: "是否可见", trigger: "change"},
        ],
        articleCover: [{required: true, message: "封面", trigger: "change"}],
        sortId: [{required: true, message: "分类", trigger: "change"}],
        labelId: [{required: true, message: "标签", trigger: "blur"}],
      },
    };
  },

  computed: {},

  watch: {
    "article.sortId"(newVal, oldVal) {
      if (oldVal !== null) {
        this.article.labelId = null;
      }
      if (!this.$common.isEmpty(newVal) && !this.$common.isEmpty(this.labels)) {
        this.labelsTemp = this.labels.filter((l) => l.sortId === newVal);
      }
    },
  },

  created() {
    this.getArticle();
    this.getSort();
    if (this.id !== undefined) {
      this.labelDisable = false;
    }
  },

  mounted() {

  },

  methods: {
    imgAdd(pos, file) {
      let form = new FormData();
      form.append("file", file);
      this.$createHttp.uploadFile(form).then((res) => {
        if (res.code === 200) {
          this.$refs.md.$img2Url(pos, res.data.path);
        } else {
          this.$message({
            message: "上传失败，请重试",
            type: "error",
          });
        }
      });
    },
    addArticleCover(res) {
      this.article.articleCover = res.path;
    },
    getSort() {
      this.$createHttp.sortSelect().then((res) => {
        if (res.code === 200) {
          this.sorts = res.data;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    getLabel(sortId) {
      this.$createHttp.labelSelect(sortId).then((res) => {
        if (res.code === 200) {
          this.labels = res.data;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    getArticle() {
      if (this.id) {
        this.$createHttp.articleInfo(this.id).then((res) => {
          if (res.code === 200) {
            for (let i in this.article) {
              this.article[i] = res.data[i]
            }
            this.getLabel(res.data.sortId)
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        });
      }
    },
    submitForm(formName) {
      if (
        this.article.encoderStatus === true &&
        this.$common.isEmpty(this.article.password)
      ) {
        this.$message({
          message: "加密时时必须输入密码！",
          type: "error",
        });
        return;
      }
      if (
        this.article.viewStatus === false &&
        this.article.recommendStatus === true
      ) {
        this.$message({
          message: "文章不可见时不可列为推荐！",
          type: "error",
        });
        return;
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.$common.isEmpty(this.id)) {
            this.saveArticle(this.article);
          } else {
            this.article.id = this.id;
            this.saveArticle(this.article);
          }
        } else {
          this.$message({
            message: "请完善必填项！",
            type: "error",
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      if (!this.$common.isEmpty(this.id)) {
        this.getArticle();
      }
    },
    sortChange(sortId) {
      this.labelDisable = false;
      this.getLabel(sortId);
    },
    saveArticle(value) {
      this.$confirm("确认保存？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
        center: true,
      }).then(() => {
        if (value.id) {
          this.$createHttp.updateArticle(value).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              setTimeout(() => {
                this.$router.go(-1)
              })
            } else {
              this.$message({
                message: res.msg,
                type: "success",
              });
            }
          });
        } else {
          this.$createHttp.addArticle(value).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.$router.go(-1)
            } else {
              this.$message({
                message: res.msg,
                type: "success",
              });
            }
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.my-tag {
  margin-bottom: 20px;
  width: 100%;
  text-align: left;
  background: var(--lightYellow);
  border: none;
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  color: var(--black);
}

.table-td-thumb {
  border-radius: 2px;
  width: 40px;
  height: 40px;
}
</style>
